import tkinter as tk
from tkinter import ttk

class SlotWidget(ttk.Frame):
    def __init__(self, parent, slot_data, resource_manager, animation_engine, widget_id):
        super().__init__(parent, width=48, height=48)
        self.slot_data = slot_data
        self.resource_manager = resource_manager
        self.animation_engine = animation_engine
        self.widget_id = widget_id
        
        self.configure(relief='raised', borderwidth=1)
        self.pack_propagate(False)
        
        self.item_label = None
        self.count_label = None
        self.tooltip_window = None
        
        self._setup_slot()
        
    def _setup_slot(self):
        """设置槽位内容"""
        if not self.slot_data:
            # 空槽位
            empty_label = ttk.Label(self, background='#E0E0E0')
            empty_label.pack(fill=tk.BOTH, expand=True)
            return
            
        # 创建物品标签
        self.item_label = ttk.Label(self, background='#E0E0E0')
        self.item_label.place(relx=0.5, rely=0.5, anchor='center')
        
        # 加载纹理
        item_id = self.slot_data.get('item', '')
        if item_id:
            texture = self.resource_manager.load_texture(item_id)
            self._update_texture(texture)
            
            # 如果是动态纹理，注册动画
            if isinstance(texture, dict) and texture.get('animated', False):
                self.animation_engine.register_animated_item(
                    self.widget_id,
                    self,
                    texture,
                    self._update_texture
                )
        
        # 数量显示 - 修复位置和样式
        count = self.slot_data.get('count', 1)
        if count > 1:
            # 使用tk.Label而不是ttk.Label以获得更多样式控制
            self.count_label = tk.Label(
                self,
                text=str(count),
                font=('Arial', 9, 'bold'),
                fg='white',  # 白色文字
                bg='#404040',  # 半透明深灰色背景
                padx=2,
                pady=0,
                bd=0,  # 无边框
                highlightthickness=0  # 无高亮边框
            )
            # 使用place精确定位在右下角
            self.count_label.place(relx=1.0, rely=1.0, anchor='se', x=-2, y=-2)
            
        # 工具提示
        self._setup_tooltip()
        
    def _update_texture(self, texture):
        """更新纹理显示"""
        if self.item_label:
            if isinstance(texture, dict):
                # 动态纹理使用当前帧
                current_frame = texture['frames'][texture['current_frame']]
                self.item_label.configure(image=current_frame)
            else:
                # 静态纹理
                self.item_label.configure(image=texture)
                
    def _setup_tooltip(self):
        """设置悬浮提示"""
        tooltip_text = self._format_tooltip()
        if not tooltip_text:
            return
            
        # 绑定事件到整个槽位和物品标签
        self.bind("<Enter>", self._show_tooltip)
        self.bind("<Leave>", self._hide_tooltip)
        if self.item_label:
            self.item_label.bind("<Enter>", self._show_tooltip)
            self.item_label.bind("<Leave>", self._hide_tooltip)
        if self.count_label:
            self.count_label.bind("<Enter>", self._show_tooltip)
            self.count_label.bind("<Leave>", self._hide_tooltip)
        
    def _show_tooltip(self, event=None):
        """显示工具提示"""
        # 如果已经有工具提示窗口，先销毁
        self._hide_tooltip()
        
        tooltip_text = self._format_tooltip()
        if not tooltip_text:
            return
            
        # 获取鼠标位置
        x = self.winfo_pointerx() + 10
        y = self.winfo_pointery() + 10
        
        # 创建工具提示窗口
        self.tooltip_window = tk.Toplevel(self)
        self.tooltip_window.wm_overrideredirect(True)
        self.tooltip_window.wm_geometry(f"+{x}+{y}")
        
        # 设置工具提示样式
        label = ttk.Label(
            self.tooltip_window,
            text=tooltip_text,
            background="#FFFFA0",
            foreground="#000000",
            relief='solid',
            borderwidth=1,
            padding=8,
            wraplength=250,
            font=('Arial', 9)
        )
        label.pack()
        
    def _hide_tooltip(self, event=None):
        """隐藏工具提示"""
        if hasattr(self, 'tooltip_window') and self.tooltip_window:
            try:
                self.tooltip_window.destroy()
            except:
                pass
            self.tooltip_window = None
        
    def _format_tooltip(self):
        """格式化工具提示文本"""
        if not self.slot_data:
            return ""
            
        lines = []
        
        # 显示名称
        display_name = self.slot_data.get('display_name')
        if display_name:
            # 移除Minecraft格式代码用于显示
            clean_name = display_name.replace('§0', '').replace('§1', '').replace('§2', '')\
                                    .replace('§3', '').replace('§4', '').replace('§5', '')\
                                    .replace('§6', '').replace('§7', '').replace('§8', '')\
                                    .replace('§9', '').replace('§a', '').replace('§b', '')\
                                    .replace('§c', '').replace('§d', '').replace('§e', '')\
                                    .replace('§f', '').replace('§k', '').replace('§l', '')\
                                    .replace('§m', '').replace('§n', '').replace('§o', '')\
                                    .replace('§r', '')
            lines.append(clean_name)
        else:
            # 使用物品ID作为备选
            item_id = self.slot_data.get('item', '未知物品')
            if ':' in item_id:
                item_name = item_id.split(':')[1].replace('_', ' ').title()
            else:
                item_name = item_id.replace('_', ' ').title()
            lines.append(item_name)
        
        # 描述
        lore = self.slot_data.get('lore', [])
        if lore:
            lines.append("")  # 空行分隔
            if isinstance(lore, list):
                for line in lore:
                    # 处理Minecraft格式代码
                    clean_line = line.replace('§0', '').replace('§1', '').replace('§2', '')\
                                    .replace('§3', '').replace('§4', '').replace('§5', '')\
                                    .replace('§6', '').replace('§7', '').replace('§8', '')\
                                    .replace('§9', '').replace('§a', '').replace('§b', '')\
                                    .replace('§c', '').replace('§d', '').replace('§e', '')\
                                    .replace('§f', '').replace('§k', '').replace('§l', '')\
                                    .replace('§m', '').replace('§n', '').replace('§o', '')\
                                    .replace('§r', '')
                    lines.append(clean_line)
            else:
                lines.append(str(lore))
        
        # 附魔
        enchantments = self.slot_data.get('enchantments', [])
        if enchantments:
            lines.append("")
            lines.append("附魔:")
            for ench in enchantments:
                ench_id = ench.get('id', '未知')
                # 简化附魔ID显示
                if ':' in ench_id:
                    ench_name = ench_id.split(':')[1].replace('_', ' ').title()
                else:
                    ench_name = ench_id.replace('_', ' ').title()
                level = ench.get('level', 1)
                lines.append(f"  {ench_name} {level}")
        
        # 数量
        count = self.slot_data.get('count', 1)
        if count > 1:
            lines.append("")
            lines.append(f"数量: {count}")
                
        return "\n".join(lines)

class PageFrame(ttk.Frame):
    def __init__(self, parent, page_data):
        super().__init__(parent)
        self.page_data = page_data
        self._setup_page()
        
    def _setup_page(self):
        """设置页面内容"""
        title = self.page_data.get('title', '')
        content = self.page_data.get('content', '')
        
        # 标题
        if title:
            title_label = ttk.Label(
                self,
                text=title,
                font=('Arial', 18, 'bold')
            )
            title_label.pack(pady=20)
            
        # 内容
        if content:
            # 使用Text控件支持多行和滚动
            text_frame = ttk.Frame(self)
            text_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
            
            text_widget = tk.Text(
                text_frame,
                wrap=tk.WORD,
                font=('Arial', 11),
                relief='flat',
                padx=10,
                pady=10
            )
            
            # 添加滚动条
            scrollbar = ttk.Scrollbar(text_frame, orient="vertical", command=text_widget.yview)
            text_widget.configure(yscrollcommand=scrollbar.set)
            
            text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
            
            # 插入文本
            text_widget.insert(tk.END, content)
            text_widget.config(state=tk.DISABLED)